<template>
  <div class="upload-container">
    <div class="upload">
      <input
        :id="uploadId"
        ref="clearFile"
        type="file"
        style="display:none"
        class="add-file-right-input"
        @change="uploadTempKeys($event)"
      >
      <div v-if="config.limit > filelist.length" class="add" @click="upload">
        <img
          v-if="type == 0"
          src="http://nzb.iccnet.cn/assets/images/lessons/idcard-front.png"
          style="width:100%;height:100%"
        >
        <img
          v-if="type == 1"
          src="http://nzb.iccnet.cn/assets/images/lessons/idcard-back.png"
          style="width:100%;height:100%"
        >
        <img
          v-if="type == 2"
          src="http://nzb.iccnet.cn/assets/images/lessons/teachercard-front.png"
          style="width:100%;height:100%"
        >
        <i v-if="type == 4" class="el-icon-plus" />
      </div>
      <template v-if="is_image">
        <div
          v-for="(itemi, indexi) in filelist"
          :key="indexi"
          @mouseenter="isShow = indexi"
          @mouseleave="isShow = -1"
        >
          <span
            v-show="isShow === indexi"
            v-if="$route.query.status != 1"
            class="shade"
          >
            <i class="el-icon-zoom-in" @click.stop="bosst(itemi.url)" />
            <template v-if="config.limit == 1">
              <i class="el-icon-refresh" @click.stop="upload" />
            </template>
            <template v-else>
              <i class="el-icon-delete" @click.stop="del(indexi)" />
            </template>
          </span>
          <el-dialog :visible.sync="dialogVisible" :append-to-body="true">
            <img width="100%" :src="preImg" alt>
          </el-dialog>
          <el-image :src="itemi.url" />
        </div>
      </template>
      <!-- <div v-show="is_file" v-for="(item, index) in filelist" :key="index" /> -->
      <!-- <div>文件名:</div> -->
    </div>
    <div v-if="type == 0" class="message">上传身份证正面</div>
    <div v-if="type == 1" class="message">上传身份证反面</div>
    <div v-if="type == 2" class="message">上传教师资格证</div>
  </div>
</template>
<script>
import compress from './js/compress'
import cos_config from './js/cos'
import { getTempKey } from '@/api/upload'
export default {
    props: ['config', 'uploadId', 'type', 'urlnow'],
    data() {
        return {
            dialogImageUrl: '',
            dialogVisible: false,
            filelist: [],
            preImg: '',
            file: [],
            temp: [],
            fileTemp: [],
            is_image: false,
            is_file: false,
            isShow: -1
        }
    },
    watch: {
        urlnow: {
            handler: function(item) {
                if (item.url === '') {
                    this.filelist = []
                }
                if (this.filelist.length === 0) {
                    //   console.log('监听：', item, this.filelist)
                    if (item && item.url) {
                        this.filelist = [item]
                    }
                } else {
                    if (item && item.url && this.temp.length == 0) {
                        this.filelist = []
                        this.filelist = [item]
                    }
                }
            },
            immediate: true
        }
    },
    mounted() {
        if (this.config.type == 'image') {
            this.is_image = true
        } else {
            this.is_file = true
        }
    },
    methods: {
        getObjectURL(file) {
            var url = null
            if (window.createObjectURL != undefined) {
                // basic
                url = window.createObjectURL(file)
            } else if (window.URL != undefined) {
                // mozilla(firefox)
                url = window.URL.createObjectURL(file)
            } else if (window.webkitURL != undefined) {
                // webkit or chrome
                url = window.webkitURL.createObjectURL(file)
            }
            return url
        },
        // 点击上传
        uploadTempKeys($e) {
            const config = this.config
            if ($e.target.files[0].type.split('/')[0] != config.type) {
                this.$message.error('上传文件类型不符合')
                return false
            }

            let url = ''
            const name = $e.target.files[0].name

            let files = $e.target.files[0]

            if (config.type == 'image') {
                compress.compressImg(files).then(res => {
                    files = res
                })
            }
            url = this.getObjectURL($e.target.files[0])
            console.log('====================================')
            console.log(url)
            console.log('====================================')
            const that = this
            if (config.limit == 1) {
                if (this.filelist.length == 0) {
                    this.file.push(files)
                    this.filelist.push({ name: name, url: url })
                    this.fileTemp.push(files)
                } else {
                    this.file[0] = files
                    this.filelist = []
                    this.filelist.push({ name: name, url: url })
                    this.fileTemp[0] = files
                }
            } else {
                if (this.filelist.length < config.limit) {
                    this.file.push(files)
                    this.filelist.push({ name: name, url: url })
                    this.fileTemp.push(files)
                } else {
                    return false
                }
            }

            for (var i = 0; i < this.fileTemp.length; i++) {
                that.getTemKey({
                    // 用户id
                    unid: 1,
                    // 文件类型
                    type: config.type,
                    // 文件后缀
                    ext: this.file[i].name.split('.')[1]
                })
                this.fileTemp.splice(i, 1)
            }
            this.$refs['clearFile'].value = ''
        },
        // 返回数据
        getTemKey(data) {
            console.log('====================================')
            console.log('data', data, this.temp.length, this.config.limit)
            console.log('====================================')
            if (this.temp.length < this.config.limit) {
                getTempKey(data).then(res => {
                    this.temp.push({
                        SecretId: res.data.credentials.tmpSecretId,
                        SecretKey: res.data.credentials.tmpSecretKey,
                        XCosSecurityToken: res.data.credentials.sessionToken,
                        StartTime: res.data.startTime, // 时间戳，单位秒，如：1580000000
                        ExpiredTime: res.data.expiredTime // 时间戳，单位秒，如：1580000900})
                    })

                    this.$emit('filepath', res.data.filepath, res.data.url)
                })
            }
        },
        async putFile(filepath) {
            console.log('temp', this.temp)
            console.log('KEY', filepath)
            for (var i = 0; i < this.temp.length; i++) {
                var COS = require('cos-js-sdk-v5')
                var cos = new COS(this.temp[i])

                // 上传图片  其中Bucket 和 Region找你们负责人拿
                // key 在前面加上路径写法可以生成文件夹
                await cos.putObject(
                    {
                        Bucket: cos_config.Bucket /* 必须 */,
                        Region: cos_config.Region /* 存储桶所在地域，必须字段 */,
                        Key: filepath[i].filepath /* 必须 */,
                        StorageClass: 'STANDARD',
                        Body: this.file[i], // 上传文件对象
                        onProgress: progressData => {
                            console.log(JSON.stringify(progressData))
                        }
                    },
                    (err, data) => {
                        // 将上传后的封面进行路径拼接保存到本地
                        console.log(err || data)
                        // 返回成功/失败
                        if (data.statusCode == 200) {
                            this.temp = []
                        }
                    }
                )
            }
        },
        upload() {
            document.getElementById(this.uploadId).click()
        },
        bosst(url) {
            this.preImg = url
            this.dialogVisible = true
        },
        del(index) {
            this.filelist.splice(index, 1)
            this.file.splice(index, 1)
            this.temp.splice(index, 1)
        }
    }
}
</script>
<style lang="scss" scoped>
.upload-container {
  width: 150px;
}
.upload {
  display: flex;
  flex-wrap: wrap;
  width: 150px;
  height: 100px;
  .el-image {
    width: 150px;
    height: 100px;
    // margin-left: 10px;
  }
}
.add {
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px dashed #d9d9d9;
  width: 150px;
  height: 100px;
  color: #8c939d;
}
.el-icon-plus {
  font-size: 25px;
}
.shade {
  width: 150px;
  height: 100px;
  position: absolute;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: space-around;
  background-color: rgba(48, 48, 48, 0.4);
  z-index: 1000;
  .el-icon-zoom-in {
    font-size: 20px;
    color: #ffff;
  }
  .el-icon-delete {
    font-size: 20px;
    color: #ffff;
  }
  .el-icon-refresh {
    font-size: 20px;
    color: #ffff;
  }
}
.message {
  margin: 10px 0px;
  color: #999;
  font-size: 14px;
  text-align: center;
}
</style>
